import base64
import pickle

from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, user, response):
    # 1 获取cookie的购物车数据
    cart_cookie = request.COOKIES.get("cart")
    # 2 如果没有数据 返回response
    if not cart_cookie:
        return response
    # 3 把数据解码转为字典
    cookie_cart_dict = pickle.loads(base64.b64decode(cart_cookie.encode()))
    # 4 把购物车字典数据转为保存redis的字典的格式
    new_cart_dict = {}  # 创建字典 保存到redis的格式的数据
    new_cart_selected_add = []
    new_cart_selected_rm = []
    for sku_id, cookie_value_dict in cookie_cart_dict.items():
    # 按照{sku_id2:2,sku_id3:5,sku_id4:8,sku_id5:10}存储
        new_cart_dict[sku_id] = cookie_value_dict['count']
    # 判断当前商品是否选中
        if cookie_value_dict["selected"]:
            new_cart_selected_add.append(sku_id)
        else:
            new_cart_selected_rm.append(sku_id)
    # 5 把转完格式的数据保存到redis hash
    redis_conn = get_redis_connection('carts')
    pl = redis_conn.pipeline()
    # 这里不会删除原来的数据，只会覆盖相同key的数据
    pl.hmset("cart_%s" % user.id, new_cart_dict)
    # 6 修改是否选中商品的状态 set
    if new_cart_selected_add:
        pl.sadd("selected_%s" % user.id, *new_cart_selected_add)
    if new_cart_selected_rm:
        pl.srem("selected_%s" % user.id, *new_cart_selected_rm)
    pl.execute()
    # 7 删除cookie数据
    response.delete_cookie('cart')
    # 8返回响应
    return response
